package auth

import (
	"context"
	"errors"
	"google.golang.org/grpc/metadata"
)

type GrpcDemoAuth struct {
	Ak, Sk string // 自定义认证内容
	UseTls bool   // 是否进行使用tls加密
}

func (g GrpcDemoAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{"ak": g.Ak, "sk": g.Sk}, nil
}

func (g GrpcDemoAuth) RequireTransportSecurity() bool {
	return g.UseTls
}

func GetFromCtx(ctx context.Context) (GrpcDemoAuth, error) {
	g := GrpcDemoAuth{}
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return g, errors.New("metadata nil")
	}
	aks := md.Get("ak")
	sks := md.Get("sk")
	if len(aks) == 0 || len(sks) == 0 {
		return g, errors.New("token error")
	}
	g.Ak = aks[0]
	g.Sk = sks[0]
	return g, nil
}
